package light.head.dao.site;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.cache.Cache;
import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.model.Category;

/**
 * 商品类型
 */
@Service
public class CategoryDAO extends BaseDAO<Category, Serializable> {
	private static final String sql_loadAll = "FROM Category c WHERE c.deleted = 0 AND c.oc = ?";
	private static final String sql_indexlist = "FROM Category c WHERE c.deleted = 0 AND c.oc = ? AND c.pc = 0";
	private static final String sql_getSonList = "FROM Category c WHERE c.deleted = 0 AND c.oc = ? AND c.pc = ?";
	public RESULT findByMap(Map<String, String> map, PageBean pageBean) {
		StringBuffer hql = new StringBuffer("FROM Category c WHERE 1 = 1");
		List<Object> list = null;
		if (map != null) {
			list = new ArrayList<Object>();
			String name = map.get(Parm.NAME);
			String deleted = map.get(Parm.DELETED);
			String oc = map.get(Parm.OC);
			if (oc != "" && isNotNull(oc)) {
				hql.append(" AND c.oc = ? ");
				list.add(Integer.parseInt(oc));
			}
			if (name != "" && isNotNull(name)) {
				hql.append(" AND c.name LIKE ? ");
				list.add("%" + name + "%");
			}
			if (deleted != "" && isNotNull(deleted)) {
				hql.append(" AND c.deleted = ?");
				list.add(Boolean.parseBoolean(deleted));
			}
		}
		hql.append(" ORDER BY c.code");

		return findToPageBean(hql.toString(), pageBean, list);
	}
	public List<Category> getAll(Integer oc) {
		 List<Category> list = Cache.categoryList;
		 if (null == list) {
			 list = loadAll(oc);
		 }
		 return list;
	 }
	
	// 查询所有类型，并保存其父子级关系
	 public List<Category> loadAll(Integer oc) {
		 List<Category> list = find(sql_loadAll,oc);
		 if (null != list && list.size() > 0) {
			 for (Category c : list) {
				 for (Category son: list) {
					 if (null == c.getSonList())
					 c.setSonList(new ArrayList<Category>());
						 
					 if (c.getCode() == son.getPc())
						 c.getSonList().add(son);
				 }
			 }
				 
		 List<Category> slist = new ArrayList<Category>();
		 	for (Category c : list) {
				if (null == c.getPc() || c.getPc() == 0) {
					slist.add(c);
				}
		 	}
			 Cache.categoryList = slist;
				return slist;
		 }
		 Cache.categoryList = null;
		 return null;
	 }
	 
	//获取首页List
	public List<Category> getIndexList(Integer code){
		List<Category> list = super.find(sql_indexlist, code);
		for(int i = 0; i<list.size(); i++){
			if(list.get(i).getCode() != null){
				list.get(i).setSonList(getSonList(code,list.get(i).getCode()));
			}
		}
		return list;
	}
	//获取子类列表
	private List<Category> getSonList(Integer oc , Integer pc){
		return super.findI(sql_getSonList, oc , pc);
	}
}
